import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import AutoImport from "unplugin-auto-import/vite";
import { appConfig } from "./appConfig/index";
import path from "path";
import fs from "fs/promises";
function bypass(req: any, res: any, options: any) {
  const proxyURL = options.target + options.rewrite(req.url);
  res.setHeader("x-req-proxyURL", proxyURL);
}
async function getgulpdata(filePath: string, mode: string) {
  let pathed = path.join(__dirname, filePath, `${mode}.json`);
  let json = await fs.readFile(pathed, { encoding: "utf-8" });
  let jsonData = !json ? { nextVersion: 1, currentVersion: 0, serviceVersion: [] } : JSON.parse(json);
  return jsonData;
}
export default async ({ mode }: { mode: "development" }) => {
  let { nextVersion } = await getgulpdata("./appConfig/gulp/", mode);
  const appConfigObj = appConfig[mode];
  return defineConfig({
    base: appConfig[mode].VITE_BASE,
    define: { appConfigObj: JSON.stringify(appConfigObj) },
    plugins: [
      vue(),
      AutoImport({
        dts: true,
        imports: [
          "vue",
          "vue-router",
          {
            "@/store/base": ["useAllStore"]
          },
          { vant: ["showToast", "showNotify"] },
          { "@/request/request_one": ["hfoRequest"] }
        ]
      }),
      Components({ resolvers: [VantResolver()], dts: true, dirs: ["src/components/common"] })
    ],
    css: { preprocessorOptions: { scss: { javascriptEnabled: true, additionalData: '@import "@/assets/css/main.scss";' } } },
    resolve: { alias: [{ find: "@", replacement: resolve(__dirname, "src") }] },
    build: {
      minify: "terser",
      terserOptions: { compress: { drop_console: false, drop_debugger: true } },
      rollupOptions: { output: { entryFileNames: `assets/[name].[hash].${nextVersion}.js`, chunkFileNames: `assets/[name].[hash].${nextVersion}.js`, assetFileNames: `assets/[name].[hash].${nextVersion}.[ext]` } }
    },
    server: {
      cors: true,
      port: appConfigObj.VITE_LOCAL_PORT,
      proxy: {
        "/api": { bypass, target: appConfigObj.VITE_PROXY_URL, changeOrigin: true, rewrite: (path) => path.replace(/api/, "") }
      }
    }
  });
};
